<template>
	<Top-Page class="qrcode-box">
		<!-- 	<cu-custom bgColor="bg-gradual-white" :isBack="true">
			<template #backText></template>
			<template #content>{{ title }}</template>
		</cu-custom> -->
		<view class="pt-20 im-flex im-align-items-center">
			<image :src="canvasUrl" class="radius-16" style="margin: 0 auto; width: 600rpx" mode="widthFix"></image>
		</view>
		<view class="padding flex items-center flex-direction mt-10" v-if="canvasUrl">
			<view class="download-btn fs-30 px-160 py-24 radius-8" @tap="saveHeadImgFile">
				<!-- #ifdef H5 -->
				下载图片
				<!-- #endif -->
				<!-- #ifndef H5 -->
				保存到相册
				<!-- #endif -->
			</view>
		</view>
		<mosowe-canvas-image
			ref="mosoweCanvasComponents"
			:lists="lists"
			:height="height"
			:width="width"
			@canvasImage="canvasImage"
		></mosowe-canvas-image>
	</Top-Page>
</template>
<script>
import mosoweCanvasImage from "@/components/mosowe-canvas-image/mosowe-canvas-image.vue"
const userInfo = uni.getStorageSync("userInfo")

export default {
	data() {
		return {
			canvasUrl: "",
			group_id: 0,
			lists: [],
			width: 375,
			height: 750,
			title: "二维码",
			contact: {},
		}
	},
	components: {
		mosoweCanvasImage,
	},
	onLoad(options) {
		this.group_id = options.group_id ? options.group_id : ""
		// 如果有团队ID就生成群聊二维码,没有就生成个人二维码
		if (options.type === "share") {
			this.title = "分享"
			uni.setNavigationBarTitle({
				title: "分享",
			})
			this.createUserQr("share")
			this.width = 500
			this.height = 700
		} else if (this.group_id) {
			this.title = "群二维码"
			uni.setNavigationBarTitle({
				title: "群二维码",
			})
			this.getGroupInfo()
		} else {
			uni.setNavigationBarTitle({
				title: "二维码",
			})
			this.createUserQr("")
		}
	},
	methods: {
		mobileFormat(mobile) {
			let pat = /(\d{3})\d*(\d{4})/
			let result = mobile.replace(pat, "$1***$2")
			return result
		},
		createUserQr(status) {
			let userInfo = uni.getStorageSync("userInfo")
			let qrUrl = userInfo.qrUrl ?? ""
			if (!qrUrl) {
				uni.showToast({
					title: "请重新登陆后再生成二维码",
					icon: "none",
				})
				uni.navigateBack()
				return
			}
			const host = "im.jwbl.top"
			let protocol
			// #ifdef H5
			protocol = window.location.protocol
			// #endif
			// #ifndef H5
			protocol = "https:"
			// #endif
			// const host = window.location.host

			/** userId 用于自动成为好友 */
			// const img_url =
			//   status === 'share'
			//     ? `https://${host}/#/pages/login/register?code=${userInfo.account}&userId=${userInfo.user_id}`
			//     : qrUrl;
			const img_url = status === "share" ? `${protocol}//${host}/download/index.html` : qrUrl
			const describe = status === "share" ? "扫一扫上面的二维码图案，下载APP" : "扫一扫上面的二维码图案，加我为好友"

			const addList = [
				// {
				// 	type: "rect",
				// 	color: "#ffffff",
				// 	width: this.width,
				// 	height: this.height,
				// 	x: 0,
				// 	y: 0,
				// },
				{
					type: "image",
					content: "/static/image/me/add-friend-bg.jpg",
					width: 375,
					height: 750,
					x: 0,
					y: 0,
				},
				{
					type: "image",
					content: userInfo.avatar,
					width: 20,
					height: 20,
					x: 138,
					y: 380,
				},
				{
					type: "text",
					content: userInfo.displayName,
					x: 165,
					y: 388,
					maxWidth: 400,
					color: "#1A1A1A",
					size: 12,
				},
				{
					type: "text",
					content: this.mobileFormat(userInfo.account),
					x: 165,
					y: 400,
					maxWidth: 400,
					color: "#808080",
					size: 10,
				},
				{
					type: "qr",
					content: img_url,
					width: 100,
					height: 100,
					x: 375 / 2 - 50,
					y: 410,
				},
				// {
				// 	type: "text",
				// 	content: describe,
				// 	x: 105,
				// 	y: 620,
				// 	color: "#999999",
				// 	maxWidth: 400,
				// 	size: 18,
				// },
			]
			const shareList = [
				{
					type: "rect",
					color: "#ffffff",
					width: this.width,
					height: this.height,
					x: 0,
					y: 0,
				},
				{
					type: "image",
					content: userInfo.avatar,
					width: 80,
					height: 80,
					x: 70,
					y: 80,
				},
				{
					type: "text",
					content: userInfo.displayName,
					x: 180,
					y: 112,
					maxWidth: 400,
					color: "#1A1A1A",
					size: 28,
				},
				{
					type: "text",
					content: this.mobileFormat(userInfo.account),
					x: 180,
					y: 145,
					maxWidth: 400,
					color: "#808080",
					size: 20,
				},
				{
					type: "qr",
					content: img_url,
					width: 360,
					height: 360,
					x: 70,
					y: 200,
				},
				{
					type: "text",
					content: describe,
					x: 105,
					y: 620,
					color: "#999999",
					maxWidth: 400,
					size: 18,
				},
			]
			this.lists = status === "share" ? shareList : addList
			console.log(this.lists, "lists")
			setTimeout(() => {
				this.$refs.mosoweCanvasComponents.createCanvas()
			}, 100)
		},
		getGroupInfo() {
			this.userList = []
			this.$api.msgApi
				.groupInfo({
					group_id: this.group_id,
				})
				.then((res) => {
					let data = res.data
					this.contact = data
					let groupName = data.name
					let length = groupName.length
					if (length > 12) {
						groupName = groupName.substring(0, 12) + "..."
					}
					this.lists = [
						{
							type: "rect",
							color: "#ffffff",
							width: this.width,
							height: this.height,
							x: 0,
							y: 0,
						},
						{
							type: "image",
							content: data.avatar,
							width: 100,
							height: 100,
							x: 140,
							y: 40,
						},
						{
							type: "text",
							content: "群聊：" + groupName,
							x: this.width / 2,
							align: "center",
							y: 180,
							maxWidth: 400,
							color: "#000",
							size: 24,
						},
						{
							type: "qr",
							content: data.qrUrl,
							width: 360,
							height: 360,
							x: 5,
							y: 220,
						},
						{
							type: "text",
							content: "该二维码7天内（" + data.qrExpire + "前）有效",
							x: 50,
							y: 640,
							color: "#999",
							maxWidth: 400,
							size: 18,
						},
					]
					setTimeout(() => {
						this.$refs.mosoweCanvasComponents.createCanvas()
					}, 100)
				})
		},
		canvasImage(e) {
			this.canvasUrl = e
		},
		// 将base64 图片保存到本地系统相册
		saveHeadImgFile() {
			// #ifdef H5
			if (window?.plus) {
				const base64Data = JSON.parse(JSON.stringify(this.canvasUrl))
				this.saveImgToAlbum(base64Data)
			} else {
				let a = document.createElement("a") // 生成一个a元素
				const name = this.contact.name || "下载" + ".jpg"
				a.download = name || "photo" // 设置图片名称
				a.href = this.canvasUrl // 将生成的URL设置为a.href属性
				a.click() // 触发a的单击事件
				setTimeout(() => {
					a.remove() //释放
				}, 1000)
			}
			// const tempLink = document.createElement('a');
			// tempLink.style.display = 'none';
			// tempLink.href = this.canvasUrl;
			// tempLink.setAttribute('download', this.contact.name + '.jpg');
			// tempLink.setAttribute('target', '_blank');
			// document.body.appendChild(tempLink);
			// tempLink.click();
			// document.body.removeChild(tempLink);

			// #endif

			// #ifndef H5
			uni.saveImageToPhotosAlbum({
				filePath: this.canvasUrl,
				success: () => {
					uni.showToast({ title: "图片保存成功", icon: "none" })
				},
			})
			// #endif
		},
		saveImgToAlbum(base64) {
			const bitmap = new plus.nativeObj.Bitmap("test")
			bitmap.loadBase64Data(
				base64,
				function () {
					const url = "_doc/" + new Date().getTime() + ".png" // url为时间戳命名方式

					bitmap.save(
						url,
						{
							overwrite: true, // 是否覆盖
							quality: "quality", // 图片清晰度
						},
						(i) => {
							window.plus.gallery.save(
								url,
								(res) => {
									uni.showToast({
										title: "保存图片到相册成功",
										icon: "none",
									})
								},
								(err) => {
									uni.showToast({
										title: "图片保存失败",
										icon: "none",
									})
								}
							)
						},
						(e) => {
							uni.showToast({
								title: "图片保存失败",
								icon: "none",
							})
							bitmap.clear()
						}
					)
				},
				(e) => {
					uni.showToast({
						title: "图片保存失败",
						icon: "none",
					})
					bitmap.clear()
				}
			)
		},
	},
}
</script>
<style lang="scss">
.qrcode-box {
	width: 750rpx;
	min-height: 100vh;
	background-color: #ffffff;
}
.list-image {
	width: 80rpx;
	height: 80rpx;
	font-size: 0;
}
.download-btn {
	text-align: center;
	color: #fff;
	background-color: #1677ff;
}
</style>
